import 'package:ceramics/extensions/ab_widget_extensions.dart';
import 'package:ceramics/model/ab_comment.dart';
import 'package:ceramics/pages/main/video/ab_video_home_page.dart';
import 'package:ceramics/pages/main/video/ab_video_item.dart';
import 'package:ceramics/util/ab_loading.dart';
import 'package:ceramics/widgets/ab_image.dart';
import 'package:flutter/material.dart' hide ModalBottomSheetRoute;
import 'package:get/get.dart';
import 'package:modal_bottom_sheet/modal_bottom_sheet.dart';

class ABCommentSheet extends StatefulWidget {
  final int videoId;
  final TextEditingController? textController;
  const ABCommentSheet({super.key,required this.videoId,this.textController});

  @override
  State<ABCommentSheet> createState() => _ABCommentSheetState();
}

class _ABCommentSheetState extends State<ABCommentSheet> with WidgetsBindingObserver {

  var _comments = <ABComment>[];
  final _focusNode = FocusNode();

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    _queryComments();
    // Future.delayed(const Duration(milliseconds: 100), () {
    //
    // });
    _focusNode.requestFocus();
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeMetrics() {

  }

  _queryComments() async {
    _comments = await ABComment.queryForVideo(widget.videoId);
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: (){
        Get.back();
      },
      child: Stack(
        children: [
          if (MediaQuery.of(context).viewInsets.bottom > 100)
            Container(
              color: Colors.transparent,
              height: Get.height,
              width: Get.width,
            ).onTap(() {
              Get.back();
            }),
          Positioned(
              bottom: MediaQuery.of(context).viewInsets.bottom,
              left: 0,
              right: 0,
              child: _buildInputRow()),
        ],
      ),
    );
  }

  Widget _buildCommentList() {
    return Container(
      height: Get.height * 0.6,
      decoration: const BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      padding: const EdgeInsets.only(top: 20),
      child: ListView.separated(itemBuilder: (ctx,idx){
        var model = _comments[idx];
        return ListTile(
          leading: ABCircleAvatar(url: model.avatarOss?.thumbUrl, size: 50),
          title: Text(model.nickname),
          subtitle: Text(model.value),
        );
      }, separatorBuilder: (ctx,idx){
        return const Divider();
      }, itemCount: _comments.length,
        physics: const ClampingScrollPhysics(),
        controller: ModalScrollController.of(context),
        padding: const EdgeInsets.only(bottom: 100),
        keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
      ),
    );
  }

  Widget _buildInputRow() {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(top: BorderSide(color: Colors.grey.shade300)),
      ),
      child: Row(
        children: [
          const SizedBox(width: 10),
          TextField(
            controller: widget.textController,
            maxLines: 3,
            focusNode: _focusNode,
            decoration: const InputDecoration(
              hintText: 'Input your comment here...',
              border: InputBorder.none,
            ),
          ).expand(),
          IconButton(onPressed: _sendComment, icon: Image.asset('images/ceramics_4.webp',scale: 3)),
          10.toHorizontalBox
        ],
      ),
    );
  }

  void _sendComment() async {
    FocusScope.of(context).unfocus();
    loading();
    var comment = ABComment.myComment(1, widget.textController?.text ?? '',videoId: widget.videoId);
    await comment.save();
    var video = Get.find<ABVideoHomePageController>().videos.firstWhere((element) => element.id == widget.videoId);
    video.commentCount.value = await ABComment.countForVideo(widget.videoId);
    await video.save();
    await Future.delayed(const Duration(seconds: 1));
    widget.textController?.clear();
    Get.find<ABVideoItemController>(tag: widget.videoId.toString()).fetchComment();
    // _queryComments();
    dismissLoading();
    Get.back();
  }
}
